<template>
	<view class="container">
		<!-- 商品轮播图 -->
		<swiper class="swiper" circular indicator-dots autoplay v-if="good.images && good.images.length">
			<swiper-item v-for="(item, index) in good.images" :key="index">
				<image :src="item" mode="aspectFill"></image>
			</swiper-item>
		</swiper>
		<!-- 默认图片 -->
		<image v-else :src="currentCover || '/static/images/default.png'" mode="aspectFill" class="default-image"></image>

		<!-- 商品信息 -->
		<view class="info-box">
			<view class="name">{{ good.name || "加载中..." }}</view>
			<view class="sales-stock">
				<text>已售 {{ good.sales || 0 }} 件</text>
				<text>库存 {{ selectedSpec ? selectedSpec.stock : "请选择规格" }} 件</text>
			</view>
			<view class="current-price" v-if="selectedSpec">
				<text class="symbol">¥</text>
				<text class="price">{{ selectedSpec.price }}</text>
			</view>
		</view>

		<!-- 规格选择 -->
		<view class="specs-box" v-if="good.specs && good.specs.length">
			<view class="header">
				<text class="title">规格</text>
				<text class="selected" v-if="!selectedSpec">请选择规格</text>
			</view>
			<view class="specs-list">
				<view class="spec-item" v-for="(item, index) in good.specs" :key="index" :class="{
					active: selectedSpec && selectedSpec.name === item.name,
					disabled: item.stock <= 0,
				}" @click="selectSpec(item)">
					<view class="spec-name">{{ item.name }}</view>
					<view class="spec-price">¥{{ item.price }}</view>
				</view>
				<view class="spec-item custom" @tap="showCustomTip">
					<view class="spec-name">
						<u-icon name="edit-pen" size="30" color="#018d71"></u-icon>
						<text>去定制</text>
					</view>
					<view class="spec-tip">专属定制</view>
				</view>
			</view>
		</view>

		<!-- 商品详情 -->
		<view class="detail-box">
			<view class="title">商品详情</view>
			<view class="description" v-if="good.description">
				<rich-text :nodes="good.description"></rich-text>
			</view>
			<view class="detail-images" v-if="good.images && good.images.length">
				<image v-for="(img, index) in good.images" :key="index" :src="img" mode="widthFix"></image>
			</view>
			<view class="empty-tip" v-else>暂无详细描述</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="left">
				<view class="btn-item" @click="navToCart()">
					<u-icon name="shopping-cart" size="40" color="#666"></u-icon>
					<text>购物车</text>
					<view class="badge" v-if="cartNum > 0">{{ cartNum }}</view>
				</view>
			</view>
			<view class="right">
				<!-- 客服按钮 -->
				<button 
					class="btn service"
					open-type="contact"
					@contact="handleContact"
				>
					<u-icon name="kefu-ermai" size="50" color="#666"></u-icon>
				</button>
				<view class="btn add-cart" @click="showBuyPopup('cart')">加入购物车</view>
				<view class="btn buy-now" @click="showBuyPopup('buy')">立即购买</view>
			</view>
		</view>

		<!-- 购买弹出层 -->
		<u-popup v-model="showPopup" mode="bottom" border-radius="20">
			<view class="popup-content">
				<view class="popup-header">
					<text class="title">{{actionType === 'cart' ? '加入购物车' : '确认订单'}}</text>
					<text class="close" @click="showPopup = false">×</text>
				</view>

				<!-- 商品信息 -->
				<view class="goods-info">
					<image :src="selectedSpec.cover" mode="aspectFill" @click="showCover(selectedSpec.cover)"></image>
					<view class="info">
						<view class="name">{{good.name}}</view>
						<view class="spec">已选：{{selectedSpec.name}}</view>
						<view class="price">¥{{selectedSpec.price}}</view>
					</view>
				</view>

				<!-- 购买数量 -->
				<view class="num-box">
					<text class="label">购买数量</text>
					<view class="num-control">
						<text class="minus" :class="{disabled: buyNum <= 1}" @click="updateNum(-1)">-</text>
						<input type="number" v-model="buyNum" @blur="checkNum"/>
						<text class="plus" :class="{disabled: buyNum >= selectedSpec.stock}" @click="updateNum(1)">+</text>
					</view>
				</view>

				<!-- 底部按钮 -->
				<view class="popup-bottom">
					<view class="total">
						<text>合计:</text>
						<text class="price">¥{{totalPrice}}</text>
					</view>
					<view class="submit" @click="submit">
						{{actionType === 'cart' ? '加入购物车' : '立即购买'}}
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 定制提示弹窗 -->
		<u-popup v-model="showCustomPopup" mode="center" round="12" @close="showCustomPopup = false">
			<view class="custom-popup">
				<view class="popup-header">
					<text class="title">联系客服定制</text>
					<view class="close" @tap="showCustomPopup = false">
						<u-icon name="close" size="28" color="#999"></u-icon>
					</view>
				</view>
				<view class="popup-content">
					<view class="tip-text">找不到合适的规格？</view>
					<view class="tip-text">点击下方客服按钮，为您专属定制！</view>
					<view class="contact-info">
						<view class="contact-item">
							<u-icon name="phone" size="36" color="#018d71"></u-icon>
							<text>{{contact.phone}}</text>
							<button class="copy-btn" @click="copyText(contact.phone)">
								<u-icon name="order" size="32" color="#999"></u-icon>
							</button>
						</view>
						<view class="contact-item">
							<u-icon name="weixin-fill" size="36" color="#07c160"></u-icon>
							<text>{{contact.weixin}}</text>
							<button class="copy-btn" @click="copyText(contact.weixin)">
								<u-icon name="order" size="32" color="#999"></u-icon>
							</button>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
		
		<u-popup v-model="showCoverPopup" mode="center" :round="10" @close="showCoverPopup = false">
			<image 
				:src="coverImage ? coverImage : ''" 
				mode="aspectFit"
			></image>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				data: {},
				userInfo: {},
				good: {
					name: "",
					price: 0,
					market_price: 0,
					sales: 0,
					stock: 0,
					cover: "",
					images: [],
					specs: [],
					description: "",
				},
				currentCover: '',
				selectedSpec: null,
				cartNum: 0,
				currentStock: 0,
				buyNum: 1,
				showPopup: false,
				actionType: 'buy', // buy或cart
				showCustomPopup: false,
				contact: {
					phone: '020-88888888',
					weixin: 'custom_xxx'
				},
				showCoverPopup: false,
				coverImage: ''
			};
		},
		computed: {
			// 计算总价
			totalPrice() {
				if(!this.selectedSpec) return 0;
				return (this.selectedSpec.price * this.buyNum).toFixed(2);
			}
		},
		methods: {
			showCover(url) {
				console.log('xx');
				this.showCoverPopup = true;
				this.coverImage = url;
			},
			// 选择规格
			selectSpec(spec) {
				if (spec.stock <= 0) {
					vk.toast("该规格已售罄");
					return;
				}
				this.selectedSpec = spec;
				this.currentCover = spec.cover;
				// 如果规格有独立价格，更新显示价格
				if (spec.price) {
					this.good.price = spec.price;
				}
				this.currentStock = spec.stock;
			},
			// 页面跳转
			navTo(url) {
				uni.navigateTo({
					url
				});
			},
			// 显示购买弹窗
			showBuyPopup(type) {
				// 检查登录状态
				if(!this.userInfo._id) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/user/login'
						})
					}, 1500)
					return
				}

				if(!this.selectedSpec) {
					uni.showToast({
						title: '请选择规格',
						icon: 'none'
					})
					return
				}
				this.actionType = type
				this.showPopup = true
			},
			// 提交购买
			submit() {
				if(this.actionType === 'cart') {
					// 加入购物车
					const cartData = {
						uid: this.userInfo._id,
						goods_id: this.good._id,
						name: this.good.name,
						cover: this.selectedSpec.cover,
						spec_name: this.selectedSpec.name,
						price: this.selectedSpec.price,
						num: this.buyNum,
						stock: this.selectedSpec.stock,
					}
					
					vk.callFunction({
						url: 'client/cart/kh/add',
						data: cartData,
						success: (data) => {
							uni.showToast({
								title: '加入购物车成功',
								icon: 'success'
							})
							// 更新购物车数量
							this.cartNum = (this.cartNum || 0) + this.buyNum
							// 重新获取最新购物车数量
							this.getCartNum()
						},
						fail: (err) => {
							console.error('加入购物车失败:', err)
							uni.showToast({
								title: '加入购物车失败',
								icon: 'none'
							})
						}
					})
				} else {
					// 立即购买,跳转到订单创建页
					const goods = [{
						goods_id: this.good._id,
						name: this.good.name,
						cover: this.selectedSpec.cover,
						spec_name: this.selectedSpec.name,
						price: this.selectedSpec.price,
						num: this.buyNum,
						total_price: this.totalPrice
					}]
					
					uni.navigateTo({
						url: `/pages/order/create?goods=${JSON.stringify(goods)}`
					})
				}
				
				this.showPopup = false
			},
			// 更新购买数量
			updateNum(value) {
				const newNum = this.buyNum + value
				if(newNum < 1 || newNum > this.selectedSpec.stock) return
				this.buyNum = newNum
			},
			// 检查购买数量
			checkNum() {
				let num = Number(this.buyNum)
				if(isNaN(num)) {
					num = 1
				} else if(num < 1) {
					num = 1
				} else if(num > this.selectedSpec.stock) {
					num = this.selectedSpec.stock
				}
				this.buyNum = num
			},
			getCartNum() {
				if(!this.userInfo._id) return
				vk.callFunction({
					url: 'client/cart/kh/getCount',
					data: {
						uid: this.userInfo._id
					},
					success: (data) => {
						if(data && data.total) {
							this.cartNum = data.total
						} else {
							this.cartNum = 0
						}
					},
					fail: (err) => {
						console.error('获取购物车数量失败:', err)
						this.cartNum = 0
					}
				})
			},
			navToCart() {
				uni.switchTab({
					url: '/pages/cart/index'
				});
			},
			// 检查未支付订单
			checkUnpaidOrder() {
				vk.callFunction({
					url: 'client/order/kh/getUnpaid',
					data: {
						uid: vk.getVuex('$user.userInfo._id'),
						status: 0,
					},
					success: (data) => {
						if(data && data.item) {
							uni.showModal({
								title: '未支付订单提醒',
								content: '您有未支付的订单，是否立即支付？',
								success: (res) => {
									if(res.confirm) {
										uni.navigateTo({
											url: `/pages/order/detail?id=${data.item._id}`
										})
									}
								}
							})
						}
					}
				})
			},
			// 处理客服会话事件
			handleContact(e) {
				console.log('客服会话事件：', e)
			},
			showCustomTip() {
				// 先关闭规格弹窗(如果打开的话)
				this.showPopup = false
				// 延迟显示定制弹窗，避免动画冲突
				setTimeout(() => {
					this.showCustomPopup = true
				}, 100)
			},
			// 复制文本
			copyText(text) {
				uni.setClipboardData({
					data: text,
					success: () => {
						uni.showToast({
							title: '复制成功',
							icon: 'success'
						})
					},
					fail(err) {
						console.log(err);
					}
				})
			},
			getContact() {
				vk.callFunction({
					url: 'client/system/pub/config',	
					success: (data) => {
						if(data.item) {
							let contactList = data.item.contact;
							if (contactList) {
								this.contact = contactList[0]
							}
							contact: {
								
							}
						}
					}
				})
			}
		},
		onLoad(e) {
			let id = e.id;
			let that = this;
			if (id) {
				vk.callFunction({
					url: "client/goods/pub/good",
					title: "请求中...",
					data: {
						id: id,
					},
					success: (data) => {
						if (data && data.item) {
							// 合并数据，保留默认值
							that.good = Object.assign({}, that.good, data.item);
							that.currentCover = data.item.cover;
						} else {
							vk.toast("商品数据加载失败");
							setTimeout(() => {
								vk.navigateBack();
							}, 1500);
						}
					},
				});
				// 获取收货地址
				that.userInfo = vk.getVuex("$user.userInfo");
				that.getCartNum();
				that.getContact();
			} else {
				vk.toast("当前商品不存在", "fail");
				vk.navigateBack();
			}
			this.checkUnpaidOrder()
		},
		// 监听 - 页面下拉刷新
		onPullDownRefresh() {
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onShow() {
			// 每次显示页面时获取最新购物车数量
			if(this.userInfo._id) {
				this.getCartNum()
			}
		},
		// 分享设置
		onShareAppMessage() {
			const goods = this.good
			return {
				title: goods.name,
				path: `/pages/goods/detail?id=${goods._id}`,
				imageUrl: goods.cover || '/static/share.png'
			}
		},
		// 分享到朋友圈
		onShareTimeline() {
			const goods = this.good
			return {
				title: goods.name,
				query: `id=${goods._id}`,
				imageUrl: goods.cover || '/static/share.png'
			}
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 100rpx;

		.swiper {
			width: 100%;
			height: 750rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.info-box {
			margin-top: 20rpx;
			padding: 30rpx;
			background-color: #fff;

			.name {
				font-size: 32rpx;
				color: #333;
				margin-bottom: 16rpx;
			}

			.sales-stock {
				display: flex;
				justify-content: space-between;
				font-size: 24rpx;
				color: #999;
			}

			.current-price {
				margin-top: 20rpx;

				.symbol {
					font-size: 32rpx;
					color: #f00;
				}

				.price {
					font-size: 48rpx;
					color: #f00;
					font-weight: bold;
				}
			}
		}

		.specs-box {
			margin-top: 20rpx;
			padding: 30rpx;
			background-color: #fff;

			.header {
				display: flex;
				justify-content: space-between;
				margin-bottom: 30rpx;

				.title {
					font-size: 32rpx;
					color: #333;
					font-weight: bold;
				}

				.selected {
					font-size: 28rpx;
					color: #999;
				}
			}

			.specs-list {
				display: flex;
				flex-wrap: wrap;
				margin: 0 -10rpx;

				.spec-item {
					width: calc(50% - 20rpx);
					margin: 10rpx;
					padding: 20rpx;
					text-align: center;
					border: 1rpx solid #ddd;
					border-radius: 12rpx;
					font-size: 28rpx;
					color: #333;
					background-color: #f8f8f8;

					.spec-name {
						margin-bottom: 8rpx;
					}

					.spec-price {
						font-size: 24rpx;
						color: #f00;
					}

					&.active {
						color: #018d71;
						border-color: #018d71;
						background-color: rgba(1, 141, 113, 0.1);

						.spec-price {
							color: #018d71;
						}
					}

					&.disabled {
						color: #999;
						border-color: #eee;
						background-color: #f5f5f5;

						.spec-price {
							color: #999;
						}
					}

					&.custom {
						border-color: #ddd;
						background: #fff;
						
						.spec-name {
							display: flex;
							align-items: center;
							color: #666;
							
							text {
								margin-left: 8rpx;
							}
						}
						
						.spec-tip {
							font-size: 24rpx;
							color: #999;
						}
						
						&:active {
							opacity: 0.8;
						}
					}
				}
			}
		}

		.detail-box {
			margin-top: 20rpx;
			padding: 30rpx;
			background-color: #fff;

			.title {
				font-size: 32rpx;
				color: #333;
				font-weight: bold;
				margin-bottom: 20rpx;
			}

			.detail-images {
				image {
					width: 100%;
					margin-bottom: 20rpx;

					&:last-child {
						margin-bottom: 0;
					}
				}
			}

			.empty-tip {
				color: #999;
				font-size: 28rpx;
				text-align: center;
				padding: 40rpx 0;
			}
		}

		.bottom-bar {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			height: 120rpx;
			background-color: #fff;
			display: flex;
			align-items: center;
			padding: 0 30rpx 10rpx;
			box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

			.left {
				display: flex;  // 让购物车和客服按钮并排
				
				.btn-item {
					position: relative;
					display: flex;
					flex-direction: column;
					align-items: center;

					text {
						font-size: 22rpx;
						color: #666;
						margin-top: 4rpx;
					}

					.badge {
						position: absolute;
						top: -10rpx;
						right: -10rpx;
						min-width: 32rpx;
						height: 32rpx;
						line-height: 32rpx;
						text-align: center;
						background-color: #f00;
						color: #fff;
						font-size: 20rpx;
						border-radius: 16rpx;
						padding: 0 8rpx;
					}

					&.service {
						margin-left: 30rpx;
						background: none;
						padding: 0;
						line-height: 1;
						
						&::after {
							border: none;
						}
						
						&:active {
							opacity: 0.7;
						}
					}
				}
			}

			.right {
				flex: 1;
				display: flex;
				justify-content: flex-end;

				.btn {
					width: 200rpx;
					height: 72rpx;
					line-height: 72rpx;
					text-align: center;
					border-radius: 36rpx;
					font-size: 28rpx;
					margin-left: 20rpx;

					&.service {
						width: 72rpx;
						padding: 0;
						margin-right: 0rpx;
						background: none;
						display: flex;
						align-items: center;
						justify-content: center;
						
						&::after {
							border: none;
						}
						
						&:active {
							opacity: 0.7;
						}
					}

					&.add-cart {
						background-color: rgba(1, 141, 113, 0.1);
						color: #018d71;
					}

					&.buy-now {
						background-color: #018d71;
						color: #fff;
					}
				}
			}
		}

		.default-image {
			width: 100%;
			height: 750rpx;
		}

		.num-box {
			margin-top: 20rpx;
			padding: 30rpx;
			background-color: #fff;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.label {
				font-size: 28rpx;
				color: #333;
			}

			.num-control {
				display: flex;
				align-items: center;

				text {
					width: 60rpx;
					height: 60rpx;
					line-height: 60rpx;
					text-align: center;
					background-color: #f5f5f5;
				}

				input {
					width: 80rpx;
					height: 60rpx;
					text-align: center;
					margin: 0 4rpx;
				}
			}
		}

		.popup-content {
			padding: 30rpx;
			max-height: 80vh;
			overflow-y: auto;

			.popup-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 30rpx;

				.title {
					font-size: 32rpx;
					font-weight: bold;
				}

				.close {
					font-size: 40rpx;
					color: #999;
				}
			}

			.goods-info {
				display: flex;
				align-items: center;
				margin-bottom: 30rpx;

				image {
					width: 120rpx;
					height: 120rpx;
					border-radius: 12rpx;
					margin-right: 20rpx;
				}

				.info {
					.name {
						font-size: 32rpx;
						color: #333;
						margin-bottom: 16rpx;
					}

					.spec {
						font-size: 28rpx;
						color: #999;
					}

					.price {
						font-size: 48rpx;
						color: #f00;
						font-weight: bold;
					}
				}
			}

			.popup-bottom {
				margin-top: 30rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.total {
					font-size: 28rpx;

					.price {
						color: #f00;
						font-size: 36rpx;
						font-weight: bold;
					}
				}

				.submit {
					width: 240rpx;
					height: 80rpx;
					line-height: 80rpx;
					text-align: center;
					background: linear-gradient(135deg, #02a584 0%, #018d71 100%);
					color: #fff;
					border-radius: 40rpx;
					font-size: 28rpx;
					box-shadow: 0 8rpx 16rpx rgba(1,141,113,0.2);
					transition: transform 0.2s;
					
					&:active {
						transform: translateY(2rpx);
					}
				}
			}
		}

		.custom-popup {
			width: 600rpx;
			padding: 40rpx 30rpx;
			
			.popup-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 30rpx;
				
				.title {
					font-size: 32rpx;
					color: #333;
					font-weight: bold;
				}
				
				.close {
					padding: 10rpx;
					
					&:active {
						opacity: 0.7;
					}
				}
			}
			
			.popup-content {
				.tip-text {
					font-size: 28rpx;
					color: #666;
					text-align: center;
					line-height: 1.8;
				}
				
				.contact-info {
					margin-top: 30rpx;
					padding: 20rpx;
					background: #f8f8f8;
					border-radius: 12rpx;
					
					.contact-item {
						display: flex;
						align-items: center;
						padding: 16rpx 0;
						
						text {
							flex: 1;
							margin-left: 20rpx;
							font-size: 28rpx;
							color: #333;
						}
						
						.copy-btn {
							background: none;
							border: none;
							padding: 10rpx;
							margin: 0;
							line-height: 1;
							
							&:active {
								opacity: 0.7;
							}
							
							&::after {
								border: none;
							}
						}
						
						&:first-child {
							border-bottom: 2rpx solid #eee;
						}
					}
				}
			}
		}
	}
</style>